package top.lakakala.util.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by k3312 on 2017/6/16.
 */
public class DisUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    private Logger logger = LoggerFactory.getLogger(DisUsernamePasswordAuthenticationFilter.class);
    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
    public static final String SPRING_SECURITY_FORM_METHOD_KEY = "method";

    public static final String SPRING_SECURITY_USERNAME_SPLIT = "/";

    public static final String SPRING_SECURITY_METHOD_STUDENT = "student";
    public static final String SPRING_SECURITY_METHOD_ADMIN = "admin";
    public static final String SPRING_SECURITY_METHOD_TEACHER = "teacher";
    private String usernameParameter = "username";
    private String passwordParameter = "password";
    private String methodParameter = "method";
    private boolean postOnly = true;

    public DisUsernamePasswordAuthenticationFilter() {
        super(new AntPathRequestMatcher("/login/doLogin", "POST"));
    }

    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            String username = this.obtainUsername(request);
            String password = this.obtainPassword(request);
            String method = this.obtainMethod(request);
            logger.debug("username={}\npassword={}\nmethod={}", username, password, method);
            if (username == null) {
                username = "";
            }

            if (password == null) {
                password = "";
            }

            if (method == null) {
                method = SPRING_SECURITY_METHOD_STUDENT;
            } else {
                method = method.trim();
            }
            HttpSession session = request.getSession();
            if (session != null) {
                session.setAttribute(MyUrlAuthenticationSuccessHandler.SPRING_SECURITY_LOGIN_METHOD, method);
            }
            username = username.trim();
            username = method + SPRING_SECURITY_USERNAME_SPLIT + username;
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }

    protected String obtainPassword(HttpServletRequest request) {
        return request.getParameter(this.passwordParameter);
    }

    protected String obtainUsername(HttpServletRequest request) {
        return request.getParameter(this.usernameParameter);
    }

    protected String obtainMethod(HttpServletRequest request) {
        return request.getParameter(this.methodParameter);
    }

    protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }

    public void setUsernameParameter(String usernameParameter) {
        Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
        this.usernameParameter = usernameParameter;
    }

    public void setPasswordParameter(String passwordParameter) {
        Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
        this.passwordParameter = passwordParameter;
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    public final String getUsernameParameter() {
        return this.usernameParameter;
    }

    public final String getPasswordParameter() {
        return this.passwordParameter;
    }
}
